<template>
  <div class="answer">
    <div class="answer_header">{{ title || '' }}</div>
    <div class="answer_form" v-for="item in formData" :key="item.id">
      <div class="answer_form_title">{{ item.title }}</div>
      <div class="answer_form_content" v-if="item.type == 1">
        <div class="flex justify_between">
          <div class="flex_1">
            <van-field
              v-model="item.value"
              placeholder="输入关键词搜索"
              :disabled="questionData.status == '1' ? true : false"
            ></van-field>
          </div>
          <div class="search" @click="searchCompany(item.value)" v-if="questionData.status !== '1'">搜索</div>
        </div>
        <div class="company_list" v-if="companyShow">
          <div
            class="company"
            v-for="(companyItem, companyIndex) in companyList"
            :key="companyIndex"
            @click="checkCompany(companyItem)"
          >
            {{ companyItem.company_name }}
          </div>
        </div>
      </div>
      <div class="answer_form_content" v-if="item.type == 2">
        <div class="calendar" @click="openCalendar">
          <div :class="item.value ? '' : 'u-color-gray'">
            {{ item.value || "请选择" }}
          </div>
          <van-icon name="calendar-o" size="24" />
        </div>
        <van-calendar
          v-model:show="calendarShow"
          position="right"
          @confirm="calendarConfirm"
        />
      </div>
      <div class="answer_form_content" v-if="item.type == 3">
        <van-radio-group v-model="item.value" :disabled="questionData.status == '1' ? true : false">
          <van-radio
            :icon-size="16"
            :name="radioItem.content"
            v-for="radioItem in item.list"
            :key="radioItem.id"
            >{{ radioItem.content }}</van-radio
          >
        </van-radio-group>
      </div>
      <div class="answer_form_content" v-if="item.type == 4">
        <van-checkbox-group v-model="item.value" :disabled="questionData.status == '1' ? true : false">
          <van-checkbox
            shape="square"
            :icon-size="16"
            :name="checkboxItem.content"
            v-for="checkboxItem in item.list"
            :key="checkboxItem.id"
            >{{ checkboxItem.content }}</van-checkbox
          >
        </van-checkbox-group>
      </div>
      <div class="answer_form_content" v-if="item.type == 5">
        <div>
          <van-field
            v-model="item.value"
            placeholder="请填写"
            type="textarea"
            :disabled="questionData.status == '1' ? true : false"
            autosize
          ></van-field>
        </div>
      </div>
      <div class="answer_form_content" v-if="item.type == 6">
        <van-field v-model="item.value" placeholder="请填写" :disabled="questionData.status == '1' ? true : false"></van-field>
      </div>
    </div>
    <div class="answer_form" v-if="questionData.status !== '1'">
      <div class="answer_form_title">16.短信验证码</div>
      <div class="answer_form_content">
        <div class="flex justify_between">
          <div class="flex_1">
            <van-field v-model="code" placeholder="输入关键词搜索"></van-field>
          </div>
          <div class="code_btn" @click="sendCode">
            {{ codeCount <= 0 ? "获取验证码" : `${codeCount}秒` }}
          </div>
        </div>
      </div>
    </div>

    <div class="form_btn_box">
      <div
        class="return_btn"
        v-if="questionData.status == '1'"
        @click="goQuestionList"
      >
        返回
      </div>
      <div class="u-width-100 flex justify_around" v-else>
        <div class="common_btn" @click="submit(1)">保存草稿</div>
        <div class="common_btn" @click="submit(2)">提交</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  getCompanyNameNew,
  getNewQuestionnaire,
  createMyQuestionnaire,
  getMyQuestionnaireDetail,
  getSmsCode,
} from "@/api/index";
import { validatePhoneNumber } from "@/util/index";
import { throttle } from "@/service/debounce";
import { Dialog } from "vant";
import { Toast } from "vant";

const router = useRouter();
const questionData = ref({}) as any; /* 问卷数据 */
const title = ref('') as any;

/* type 1 公司搜索  2 日期  3 单选  4 多选  5 多行文本  6 文本  7 验证码   */
const formData = reactive([]);
const companyList = ref([]);

const companyShow = ref(false);
const calendarShow = ref(false);
const code = ref("");
const codeCount = ref(0);
const codeStatus = ref(true);

const getQuestion = async () => {
  const res = await getNewQuestionnaire();
  title.value = res.title;
  res.problem.map((item) => {
    switch (item.id) {
      case 1:
      case 2:
        const params = {
          id: item.id,
          type: item.id,
          title: item.problem,
          value: "",
        };
        formData.push(params);
        break;
      case 3:
      case 11:
        const radioParams = {
          id: item.id,
          type: 3,
          title: item.problem,
          list: item.option,
          value: "",
        };
        formData.push(radioParams);
        break;
      case 10:
      case 12:
        const checkParams = {
          id: item.id,
          type: 4,
          title: item.problem,
          list: item.option,
          value: [],
        };
        formData.push(checkParams);
        break;
      case 4:
      case 5:
      case 6:
      case 7:
      case 8:
      case 9:
      case 13:
        const textParams = {
          id: item.id,
          type: 5,
          title: item.problem,
          value: "",
        };
        formData.push(textParams);
        break;
      case 14:
      case 15:
        const inputParams = {
          id: item.id,
          type: 6,
          title: item.problem,
          value: "",
        };
        formData.push(inputParams);
        break;
      case 16:
        const codeParams = {
          id: item.id,
          type: 7,
          title: item.problem,
          value: "",
        };
        formData.push(codeParams);
        break;
    }
  });
};

const getQuestionDetial = async (val: any) => {
  const res = await getMyQuestionnaireDetail({
    common_questionnaire_user_id: val,
  });
  title.value = res.title;
  res.problem.map((item) => {
    switch (item.id) {
      case 1:
      case 2:
        const params = {
          id: item.id,
          type: item.id,
          title: item.problem,
          value: item.answer,
        };
        formData.push(params);
        break;
      case 3:
      case 11:
        item.option.map((radioItem) => {
          if (radioItem.id == Number(item.answers.answers)) {
            const radioParams = {
              id: item.id,
              type: 3,
              title: item.problem,
              list: item.option,
              value: radioItem.content,
            };
            formData.push(radioParams);
          }
        });
        break;
      case 10:
      case 12:
        let checkArray = item.answers.answers.split(",")
        let checkName = []
        item.option.map(checkItem=>{
            let id = checkItem.id.toString()
            if(checkArray.includes(id)){
                checkName.push(checkItem.content)
            }
        })
        const checkParams = {
          id: item.id,
          type: 4,
          title: item.problem,
          list: item.option,
          value: checkName,
        };
        formData.push(checkParams);
        break;
      case 4:
      case 5:
      case 6:
      case 7:
      case 8:
      case 9:
      case 13:
        const textParams = {
          id: item.id,
          type: 5,
          title: item.problem,
          value: item.answer,
        };
        formData.push(textParams);
        break;
      case 14:
      case 15:
        const inputParams = {
          id: item.id,
          type: 6,
          title: item.problem,
          value: item.answer,
        };
        formData.push(inputParams);
        break;
      case 16:
        const codeParams = {
          id: item.id,
          type: 7,
          title: item.problem,
          value: "",
        };
        formData.push(codeParams);
        break;
    }
  });
};

if (useRoute().query.id) {
  questionData.value = useRoute().query;
  getQuestionDetial(questionData.value.id);
} else {
  getQuestion();
}

const formatDate = (date:any) => {
  /**
   * @methods 日期格式转换
   */

  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};

const searchCompany = async (val: any) => {
  /**
   * @methods 搜索公司列表
   */
  if (!val) {
    Toast("请输入公司关键词");
  } else {
    const res = await getCompanyNameNew({ company_name: val });
    companyList.value = res.list;
    companyShow.value = true;
  }
};

const checkCompany = (val: any) => {
  /**
   * @methods 选中公司名
   */
  formData.map((item) => {
    if (item.id == 1) item.value = val.company_name;
  });
  companyShow.value = false;
};

const openCalendar = () => {
  /**
   * @methods 打开日历
   */
  calendarShow.value = true;
};

const calendarConfirm = (date: any) => {
  /**
   * @methods 选中日期
   */
  formData.map((item) => {
    if (item.id == 2) item.value = formatDate(date);
  });
  calendarShow.value = false;
};

const sendCode = async (val: any) => {
  /**
   * @methods 发送验证码
   */
  const mobile = formData.filter((item) => item.id == 15)[0].value;
  if (!validatePhoneNumber(mobile)) {
    Toast("请输入正确手机号");
  } else {
    if (codeStatus.value) {
      await getSmsCode({ phone: mobile });
      codeStatus.value = false;
      codeCount.value = 60;
      const countInterval = setInterval(() => {
        codeCount.value--;
        if (codeCount.value <= 0) {
          codeStatus.value = true;
          clearInterval(countInterval);
        }
      }, 1000);
    }
  }
};

const dataProcess = (val: any) => {
  /**
   * @methods 提交携带参数处理
   */
  let content = [];
  let phone = "";
  formData.map((item) => {
    if ([1, 2, 4, 5, 6, 7, 8, 9, 13, 14, 15].includes(item.id)) {
      const params = {
        problem: item.id,
        option: item.value,
      };
      content.push(params);
      phone = item.id == 15 ? item.value : "";
    } else if ([3, 11].includes(item.id)) {
      let radioArray = [];
      item.list.map((radioItem) => {
        if (radioItem.content == item.value) {
          radioArray.push(radioItem.id);
        }
      });
      const params = {
        problem: item.id,
        option: radioArray || '',
      };
      content.push(params);
    } else {
      let checkArray = [];
      item.list.map((checkboxItem) => {
        if (item.value.includes(checkboxItem.content)) {
          checkArray.push(checkboxItem.id);
        }
      });
      const params = {
        problem: item.id,
        option: checkArray || '',
      };
      content.push(params);
    }
  });
  const params = {
    type: val,
    common_questionnaire_user_id: questionData.value.id || "",
    content: content,
    phone: phone,
    code: code.value,
  };
  return params;
};

const submit = throttle(function (val: any) {
  if (val == 1) {
    createMyQuestionnaire(dataProcess(1)).then(res=>{
            Toast("保存成功")
            setTimeout(() => {
                router.push({path: '/answerSheet/list'})
            }, 1000);
        })
  } else {
    let result = formData.every((item) => {
      return item.value;
    });
    if (result && code.value) {
      createMyQuestionnaire(dataProcess(2)).then((res) => {
        Toast("提交成功");
        setTimeout(() => {
          router.push({ path: "/answerSheet/list" });
        }, 1000);
      });
    } else {
      Toast("必填项不能为空");
    }
  }
}, 2000);

const goQuestionList = () => {
  /**
   * @methods 返回列表
   */
  router.push({ path: "/answerSheet/list" });
};
</script>

<style lang="less" scoped>
.u-color-gray {
  color: #c8c9cc;
}

.u-width-100 {
  width: 100%;
}

:deep(.van-cell) {
  padding: 5px 10px;
}

:deep(.van-radio) {
  padding: 4px 0;
}

:deep(.van-checkbox) {
  padding: 4px 0;
}

.answer {
  .answer_header {
    width: 90%;
    margin: 0 auto;
    line-height: 1.5;
    text-align: center;
    padding: 30px 0;
    font-size: 17px;
  }

  .answer_form {
    width: 90%;
    margin: 0 auto;
    margin-bottom: 10px;
    .answer_form_title {
      font-size: 14px;
    }

    .answer_form_title::before {
      content: "*";
      color: red;
    }

    .answer_form_content {
      padding: 10px 0;
      position: relative;

      .search {
        background: #2c76ed;
        color: #fff;
        padding: 0 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
        font-size: 13px;
      }

      .company_list {
        width: 94%;
        margin: 0 auto;
        position: absolute;
        background-color: #868b9a;
        z-index: 10;
        padding: 0 10px;
        height: 160px;
        top: 40px;
        left: 0;
        overflow: auto;
        color: #fff;
        border-radius: 5px;

        .company {
          margin-top: 10px;
        }
      }

      .code_btn {
        background: #000;
        color: #fff;
        padding: 0 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
        font-size: 13px;
      }

      .calendar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 5px 10px;
        background: #fff;
      }
    }
  }

  .form_btn_box {
    display: flex;
    justify-content: space-around;
    margin: 20px 20px 30px 20px;

    .common_btn {
      background: #2c76ed;
      color: #fff;
      padding: 15px 0;
      border-radius: 5px;
      width: 130px;
      text-align: center;
    }

    .return_btn {
      background: #666;
      color: #fff;
      padding: 15px 0;
      border-radius: 5px;
      text-align: center;
      width: 100%;
    }
  }
}

@media (min-width: 750px) {
  .answer {
    .answer_header {
      width: 90%;
      margin: 0 auto;
      line-height: 1.5;
      text-align: center;
      padding: 30px 0;
      font-size: 17px;
    }

    .answer_form {
      width: 90%;
      margin: 0 auto;
      margin-bottom: 10px;
      .answer_form_title {
        font-size: 14px;
      }

      .answer_form_title::before {
        content: "*";
        color: red;
      }

      .answer_form_content {
        padding: 10px 0;
        position: relative;

        .search {
          background: #2c76ed;
          color: #fff;
          padding: 0 10px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 5px;
          font-size: 13px;
        }

        .company_list {
          width: 94%;
          margin: 0 auto;
          position: absolute;
          background-color: #868b9a;
          z-index: 10;
          padding: 0 10px;
          height: 160px;
          top: 40px;
          left: 0;
          overflow: auto;
          color: #fff;
          border-radius: 5px;

          .company {
            margin-top: 10px;
          }
        }

        .calendar {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 5px 10px;
          background: #fff;
        }

        .code_btn {
          background: #000;
          color: #fff;
          padding: 0 10px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 5px;
          font-size: 13px;
        }
      }
    }

    .form_btn_box {
      display: flex;
      justify-content: space-around;
      margin: 20px 20px 30px 20px;

      .common_btn {
        background: #2c76ed;
        color: #fff;
        padding: 15px 0;
        border-radius: 5px;
        width: 130px;
        text-align: center;
      }

      .return_btn {
        background: #666;
        color: #fff;
        padding: 15px 0;
        border-radius: 5px;
        text-align: center;
        width: 100%;
      }
    }
  }
}
</style>
